﻿using SumPower.MailAccount.Web.Models;
using SumPower.MailAccount.Web.XMail263Service;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml;
using System.Xml.Serialization;
using SumPower.MailAccount.Web.Code;

namespace SumPower.MailAccount.Web.Controllers
{
    [AllowAnonymous]
    public class AccountController : Controller
    {
        private readonly string key;
        private readonly string domain;
        private readonly string account;
        private static List<MailInfo.Mail> mailList;

        public AccountController()
        {
            key = ConfigurationManager.AppSettings["key"];
            domain = ConfigurationManager.AppSettings["domain"];
            account = ConfigurationManager.AppSettings["account"];
        }

        public object XmlDeserialize(string filename, Type entityType)
        {
            object obj = null;
            using (System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(entityType);
                obj = serializer.Deserialize(stream);
            }
            return obj;
        }


        public ActionResult SignIn(string returnUrl, string domain)
        {
            ViewBag.ReturnUrl = returnUrl;

            string mailFileName = Server.MapPath("~/") + "MailInfo.xml";
            MailInfo mailInfo = XmlDeserialize(mailFileName, typeof(MailInfo)) as MailInfo;
            mailList = mailInfo.Mails;
            List<SelectListItem> domainList = SetDomainList(domain, mailInfo.Mails);

            ViewBag.DomainList = domainList;
            return View("SignIn");

        }

        private static List<SelectListItem> SetDomainList(string domain, List<MailInfo.Mail> mails)
        {
            List<SelectListItem> domainList = new List<SelectListItem>();
            if (string.IsNullOrEmpty(domain) || domain.Equals("@samples.cn"))
            {
                domainList.Add(new SelectListItem() { Text = "@samples.cn", Selected = true });
            }
            else
            {
                domainList.Add(new SelectListItem() { Text = "@samples.cn" });
            }
            foreach (var item in mails)
            {
                if (item.Domain.Equals(domain))
                {
                    domainList.Add(new SelectListItem() { Text = item.Domain, Selected = true });
                }
                else
                {
                    domainList.Add(new SelectListItem() { Text = item.Domain });
                }
            }
            return domainList;
        }

        [HttpPost]
      //  [ValidateAntiForgeryToken]
        public ActionResult SignIn(SignInInfo signInModel, string returnUrl, string domain)
        {
            ViewBag.ReturnUrl = returnUrl;
            if (domain == "@samples.cn")
            {
                if (!Authenticate(signInModel.UserName, signInModel.Password))
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                    List<SelectListItem> domainList = SetDomainList(domain, mailList);
                    ViewBag.DomainList = domainList;
                    return View(signInModel);
                }
                //string userName = signInModel.UserName.Trim().Replace("@samples.cn", string.Empty);
                //FormsAuthentication.SetAuthCookie(userName, signInModel.RememberMe);
            }
            else
            {
                var mailInfo = mailList.Find(m => m.Domain == domain);
                if (!SumPower.MailAccount.Web.Code.MailAccount.Authenticate(signInModel.UserName + domain, signInModel.Password, mailInfo.Server))
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                    List<SelectListItem> domainList = SetDomainList(domain, mailList);
                    ViewBag.DomainList = domainList;
                    return View(signInModel);
                }
                else
                {
                    UserInfo user = new UserInfo();
                    user.Name = signInModel.UserName + domain; 
                    user.Userid = signInModel.UserName + domain;
                    // user.Domain = domain;
                    Session["User"] = user;
                }
            }
            //string userName = signInModel.UserName.Trim().Replace(domain, string.Empty);
            //FormsAuthentication.SetAuthCookie(userName, signInModel.RememberMe);
            FormsAuthentication.SetAuthCookie(signInModel.UserName + domain, signInModel.RememberMe);
            if (!string.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return Redirect("~/");
            }
        }
        private bool Authenticate(string userName, string password)
        {
            //在引用WebService生成的代码的Reference.cs文件中将“http://macom.263.net/axis/xmapi”替换为"http://xmapi.webservices.ma.net263.com"
            //一定要注意不能整个解决方案中替换，一定要在当前文件中远的
            Session["User"] = null;

            //如果用户邮箱帐号输全，则替换掉，只保留帐号
            userName = userName.Trim().Replace("@samples.cn", string.Empty);
            XmapiImplService xmapiImplService = new XmapiImplService();

            string sign = Md5Sign(userName + domain + password + key);
            //263验证登录，返回0成功，其他失败
            int result = xmapiImplService.authentication_New(userName, domain, password, 0, account, sign);
            if (result == 0)
            {
                //当验证通过后，从263获取用户信息
                //userid + domain + 接口账号 + 接口密钥 
                sign = Md5Sign(userName + domain + account + key);
                string userXml = xmapiImplService.getUserInfo_New(userName, domain, account, sign);
                if (!string.IsNullOrEmpty(userXml))
                {
                    UserInfo user = new UserInfo();
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(userXml);

                    XmlNode userNode = xmlDocument.SelectSingleNode("user");
                    user.Userid = userNode["userid"].InnerText;
                    user.Name = userNode["name"].InnerText;
                    user.Departmentid = userNode["departmentid"].InnerText;
                    user.Office = userNode["office"].InnerText;
                    user.Mobile = userNode["mobile"].InnerText;
                    user.Phone = userNode["phone"].InnerText;
                    user.Fax = userNode["fax"].InnerText;

                    Session["User"] = user;
                }
            }
            return result.Equals(0) && Session["User"] != null;
        }

        private string Md5Sign(string value)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] buffer = Encoding.Default.GetBytes(value);
            string result = BitConverter.ToString(md5.ComputeHash(buffer));
            return result.Replace("-", "").ToLower();

        }

        public ActionResult SignOut(string returnUrl)
        {
            FormsAuthentication.SignOut();
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("SignIn");
            }
            else
            {
                return Redirect(returnUrl);
            }
        }
    }
}